import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { AtTextarea, AtImagePicker, AtList, AtListItem, AtButton, AtMessage } from 'taro-ui'
import './fabudongtai.scss'
import { $navigateTo, $redirectTo } from '../../../../global';
import reactMixin from 'react-mixin';
import myJs from './fabudongtaiJs.js'
import app from '../../../../main';
export default class Fabudongtai extends Component {
    config = {
        navigationBarTitleText: '发布动态'
    }
    constructor() {
        super(...arguments);
        this.state = this.getData();
    }
    init() {
    }
    go(url) {
        $navigateTo(url)
    }
    no() {
        Taro.atMessage({
            'message': '请输入内容',
            'type': 'info'
        })
    }
    publish() {
        var me = this;
        var images = me.state.images;
        var arrImg = [];
        var topic_id = me.state.topic_id || 0;
        var tmp = me.state.video;
        let blur = me.$router.params.blurl
        console.log('传过来的',blur)
        if (me.state.content == '' || me.state.content == 'undefined') {
            Taro.atMessage({
                'message': '请输入内容',
                'type': 'info'
            })
            return;
        }
        if(me.state.type == '视频') {
            me.uploadVideo(tmp);
        } else {
            for (var i = 0; i < images.length; i++) {
                arrImg.push(images[i].url)
            }

            var data = (function () {
                let content = me.$router.params.blurl ?  `病历链接${blur}:`+ (me.state.content.indexOf("病历链接")==0 ?me.state.content.substring(5,me.state.content.length) : me.state.content) :me.state.content;
                if (arrImg.length <= 0 && me.state.type != '视频') {
                    if(me.$router.params.blurl){
                        content = `病历链接${blur}:`+ (me.state.content.indexOf("病历链接")==0 ?me.state.content.substring(5,me.state.content.length) : me.state.content) ;
                        console.log('病历链接ccc',content);
                        return data = {
                            content_type: '病历',
                            content: content,
                            images: arrImg,
                            type: '文本',
                            topic_id: topic_id,
                        }
                    }
                    return data = {
                        content_type: me.$router.params.blurl ? '病历' : '文本',
                        content: content,
                        images: arrImg,
                        type: me.state.type,
                        topic_id: topic_id,
                    }
                } else {
                    return data = {
                        content_type: me.$router.params.blurl ? '病历' : '文本',
                        content: content,
                        images: arrImg,
                        type: me.state.type,
                        topic_id: topic_id,
                    }
                }
            })();
            console.log("修改后的data",data)
            app.post('web/dynamic_topic/publishDynamic', data, function (res) {
                var status = res.data.status;
                console.log(res.data)
                if (status == 200) {
                    console.log('成功了')
                    if(blur){
                        let content = `病历链接${blur}:`;
                        console.log('成功了',blur)
                        app.redirectTo(`../dongtaishouye/dongtaishouye?blurl=${content}`)
                    }
                        app.redirectTo('../dongtaishouye/dongtaishouye')
                    // Taro.navigateBack({
                    //     delta: 1
                    // })
                }else{console.log('上传失败')}
            })
        }
    }
        handleTextareaChange(name, e) {
            var me = this;
            var content = e.detail.value;
            me.setState({
                content: content
            })
        }
        changeImage(files, type, index) {
            if (type == 'add') {
                console.log(files);
                this.uploadImage(files);
            }

            if (type == 'remove') {
                var images = this.state.images;
                images.splice(index, 1);
                this.setState({
                    images: images
                })
        }
    }

    // 上传图片
    uploadImage(files) {
        var me = this;
        me.setState({
            images: files
        })
        Taro.showLoading({
            title: '发布中...'
        })

        for (let i = 0; i < files.length; i++) {
            Taro.uploadFile({
                url: app.apiUri + '/admin/upload/image',
                filePath: files[i].url,
                name: 'file',
                formData: {
                    name: 'file'
                }
            }).then(function (res) {
                console.log("服务器返回数据", res)
                if (res.statusCode == 413) {
                    app.toast('文件过大，请重新上传');
                    let d = 0;
                    files.pop();
                    console.log("有"+ String(d++) +"过大")
                    return;
                }
                var result = JSON.parse(res.data);
                var path = result.result;
                console.log("返回来的图片路径", path)
                files[i].url = path;
                me.setState({
                    images: files
                });
                Taro.hideLoading();
            })
        }
    }
    //上传视频
    uploadVideo(tmp) {
        var me = this;
        Taro.showLoading({
            title: '发布中...'
        })
        let content = me.state.content
        if(me.$router.params.blurl){
            content = `病历链接${blur}:`+ (me.state.content.indexOf("病历链接")==0 ?me.state.content.substring(5,me.state.content.length) : me.state.content) ;
        }
        Taro.uploadFile({
            url: app.apiUri + '/admin/upload/image',
            filePath: tmp,
            name: 'file',
            formData: {
                name: 'file'
            },
            success(res) {
                if (res.statusCode == 413) {
                    app.toast('文件过大，请重新上传');
                    return;
                }
                var result = JSON.parse(res.data);
                var path = result.result;
                var data = {
                        content_type: me.$router.params.blurl ?'病历':'文本',
                        content: content,
                        video: path,
                        type: me.state.type,
                        topic_id: me.state.topic_id || 0
                    }
                app.post('web/dynamic_topic/publishDynamic', data, function (res) {
                    var status = res.data.status;
                    console.log(res.data)
                    Taro.hideLoading();
                    if (status == 200) {
                        app.redirectTo('../dongtaishouye/dongtaishouye')
                    }else{
                        console.log('上传失败')
                    }
                })
                Taro.hideLoading();
            }
        })
    }
    render() {
        return (
            <View className='fabudongtai'>
                <View className=' class_0'>
                    <View className=' class_1'>
                        <AtTextarea
                            count={true}
                            placeholder='写点什么'
                            onChange={this.handleTextareaChange.bind(this, 'content')}
                            value={this.state.content}
                        >
                        </AtTextarea>
                    </View>

                    {this.state.type == '图片' ?
                        <AtImagePicker
                            multiple
                            count={99}
                            files={this.state.images}
                            onChange={this.changeImage.bind(this)}
                        />
                        :
                        <view class="container">
                            <video controls={true} initial-time='0.01' src={this.state.video}></video>
                        </view>
                    }


                    {/* <AtList hasBorder={false}>
                        <AtListItem onClick={this.go.bind(this,'../dongtaihaoyou/dongtaihaoyou')} title='@ 提醒谁看' hasBorder={false} arrow='right'></AtListItem>
                    </AtList> */}
                    <AtButton type='primary' onClick={this.publish.bind(this)}>点击发表</AtButton>
                </View>
                <View>
                    <AtMessage />
                </View>
            </View>
        );
    }
}
reactMixin.onClass(Fabudongtai, myJs);